package com.qf.kdxf.util.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.ArrayList;

@Component
public class XunfeiOCRParser {

    /**
     * 解析讯飞OCR返回的JSON结果
     * @param jsonResult 讯飞API返回的JSON字符串
     * @return 解析后的文本内容
     */
    public static String parseOCRResult(String jsonResult) {
        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
        String code = jsonObject.getString("code");

        // 检查返回码
        if (!"0".equals(code)) {
            String errorMsg = jsonObject.getString("desc");
            return "识别失败: " + errorMsg;
        }

        try {
            JSONObject data = jsonObject.getJSONObject("data");
            if (data == null) {
                return "未找到有效数据";
            }

            List<String> resultLines = new ArrayList<>();
            JSONArray blocks = data.getJSONArray("block");

            // 遍历所有区块
            for (int i = 0; i < blocks.size(); i++) {
                JSONObject block = blocks.getJSONObject(i);

                // 只处理文本类型的区块
                if ("text".equals(block.getString("type"))) {
                    JSONArray lines = block.getJSONArray("line");

                    // 遍历所有行
                    for (int j = 0; j < lines.size(); j++) {
                        JSONObject line = lines.getJSONObject(j);
                        JSONArray words = line.getJSONArray("word");
                        StringBuilder lineBuilder = new StringBuilder();

                        // 遍历所有单词
                        for (int k = 0; k < words.size(); k++) {
                            JSONObject word = words.getJSONObject(k);
                            lineBuilder.append(word.getString("content"));
                        }

                        resultLines.add(lineBuilder.toString());
                    }
                }
            }

            // 将结果拼接成字符串
            return String.join("\n", resultLines);
        } catch (Exception e) {
            return "解析结果时出错: " + e.getMessage();
        }
    }

    /**
     * 通用解析方法（支持不同OCR服务）
     * @param jsonResult 讯飞API返回的JSON字符串
     * @param resultPath 结果路径（如 "data.block[].line[].word[].content"）
     * @return 解析后的文本内容
     */
    public static String parseGenericResult(String jsonResult, String resultPath) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(jsonResult);
            String code = jsonObject.getString("code");

            if (!"0".equals(code)) {
                return "识别失败: " + jsonObject.getString("desc");
            }

            // 分割结果路径
            String[] pathSegments = resultPath.split("\\.");
            Object current = jsonObject;

            for (String segment : pathSegments) {
                if (current == null) break;

                if (segment.endsWith("[]")) {
                    // 处理数组
                    String key = segment.substring(0, segment.length() - 2);
                    if (current instanceof JSONObject) {
                        current = ((JSONObject) current).getJSONArray(key);
                    }
                } else {
                    // 处理对象
                    if (current instanceof JSONObject) {
                        current = ((JSONObject) current).get(segment);
                    } else if (current instanceof JSONArray) {
                        // 数组中的对象
                        List<Object> results = new ArrayList<>();
                        for (Object item : (JSONArray) current) {
                            if (item instanceof JSONObject) {
                                results.add(((JSONObject) item).get(segment));
                            }
                        }
                        current = results;
                    }
                }
            }

            // 处理最终结果
            return formatResult(current);
        } catch (Exception e) {
            return "解析结果时出错: " + e.getMessage();
        }
    }

    private static String formatResult(Object result) {
        if (result == null) {
            return "";
        }

        if (result instanceof String) {
            return (String) result;
        }

        if (result instanceof JSONArray) {
            List<String> items = new ArrayList<>();
            for (Object item : (JSONArray) result) {
                items.add(item.toString());
            }
            return String.join("\n", items);
        }

        if (result instanceof List) {
            return String.join("\n", (List<String>) result);
        }

        return result.toString();
    }
}